import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  HttpStatus,
  BadRequestException,
} from '@nestjs/common';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { formatDates } from './../utils';
export interface Respond<T> {
  code: number;
  data: T;
  message: any;
}

@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<T, Respond<T>> {
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<Respond<T>> {
    return next.handle().pipe(
      map((data) => {
        const httpContext = context.switchToHttp();
        const req = httpContext.getRequest(); // 请求对象
        const res = httpContext.getResponse(); // 响应对象

        // post请求可能是201，都统一改成200
        if ('POST' === req.method) res.status(HttpStatus.OK);

        return {
          code: HttpStatus.OK,
          data: formatDates(data),
          message: 'success',
        };
      }),
      catchError((error) => {
        // ExceptionFilter中会进行拦截
        return throwError(() => error);
      }),
    );
  }
}
